package it.polimi.swimv2.session;

import it.polimi.swimv2.entities.AbstractUser;
import it.polimi.swimv2.entities.Admin;
import it.polimi.swimv2.entities.User;
import it.polimi.swimv2.exception.LoginManagerException;
import it.polimi.swimv2.remote.LoginManagerRemote;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class LoginManager
 */
@Stateless
public class LoginManager implements LoginManagerRemote {
	@PersistenceContext(unitName = "swimv2")
	private EntityManager em;

	/**
	 * Default constructor.
	 */
	public LoginManager() {
	}

	@Override
	public UserRole authenticate(String username, String password)
			throws LoginManagerException {
		AbstractUser u = em.find(AbstractUser.class, username);
		if (u == null || u.checkPassword(password) == false) {
			throw new LoginManagerException();
		}
		if (u.getClass()==User.class) {
			return UserRole.User;
		}
		if(u.getClass()==Admin.class){
			return UserRole.Admin;
		}
		throw new LoginManagerException();
	}
}
